<?php

namespace Wechat\Controller;
use Think\Controller;

vendor('wxpay.WxPay#Api');
vendor('wxpay.WxPay#Notify');

class NotifyController extends Controller {


    public function _initialize()
    {
        header("Content-Type:text/html; charset=utf-8");
    }

    public function wxpay_notify() {
        $notify = new PayNotifyCallBack();
        $notify->Handle(false);
    }

}


class PayNotifyCallBack extends \WxPayNotify
{
    //查询订单
    public function Queryorder($transaction_id)
    {
        $input = new \WxPayOrderQuery();
        $input->SetTransaction_id($transaction_id);
        $result = \WxPayApi::orderQuery($input, 30);
        if(array_key_exists("return_code", $result)
            && array_key_exists("result_code", $result)
            && $result["return_code"] == "SUCCESS"
            && $result["result_code"] == "SUCCESS")
        {
            return true;
        }
        return false;
    }

    //重写回调处理函数
    public function NotifyProcess($data, &$msg)
    {
        if (!array_key_exists("transaction_id", $data)) {
            $msg = "输入参数不正确";
            trace($msg, '', 'DEBUG', true);
            return false;
        }
        //查询订单，判断订单真实性
        if (!$this->Queryorder($data["transaction_id"])) {
            $msg = "订单查询失败";
            trace($msg, '', 'DEBUG', true);
            return false;
        }

        $order = M('Order')->where(array('order_sn' => $data['out_trade_no']))->find();
        if (empty($order)) {
            $msg = "订单查询失败";
            return false;
        }

        if ($data['total_fee'] != ($order['pay_amount']*100)){
            $msg = "订单金额不符";
            return false;
        }
        if ($order['order_state'] != 1) {
            $msg = "订单查询失败";
            return false;
        }

        $model = D();
        try {
            $model->startTrans();
            $orderArr = array();
            $orderArr['pay_time'] = strtotime($data['time_end']);
            $orderArr['pay_sn'] = $data['transaction_id'];
            $orderArr['update_time'] = time();
            $orderArr['pay_state'] = 1;
            $orderArr['order_state'] = 2;
            $result = M('order')->where(array('order_id' => $order['order_id']))->save($orderArr);

            //使用代金券
            if ($order['coupon_sn']){
                M('MemberCoupon')->where(array('coupon_sn' => $order['coupon_sn'], 'member_id' => $order['member_id']))->save(array('status' => 2, 'use_time' => time()));
            }

            //更新会员购买次数及最后购买时间
            $memberData = array();
            $memberData['last_buy_time'] = $order['create_time'];
            $memberData['order_count'] = array('exp','order_count+1');
            M('Member')->where(array('member_id' => $order['member_id']))->save($memberData);

            // 每次都送代金券
            $sendCoupon = getConfig('order_send_coupon');
            $couponID = getConfig('order_send_coupon_id');
//            $where = array('member_id' => $order['member_id'], 'coupon_id' => $couponID , 'status' => 1);
//            $orderCoupon = M('MemberCoupon')->where($where)->find();
            if ($sendCoupon){
                addMemberCoupon($order['member_id'], $couponID, 0);
            }

            // 邀请下单送券
            $inviteCoupon = getConfig('invite_coupon');
            if ($inviteCoupon) {
                $invite = M('MemberInvite')->where(['invite_member_id' => $order['member_id']])->find();
                if (!empty($invite) && $invite['is_order'] == 0) {
                    $couponID = getConfig('invite_coupon_id');
                    $coupon = M('Coupon')->where(array('coupon_id' => $couponID, 'status' => 1))->find();
                    if (!empty($coupon)) {
                        $memberCoupon = M('MemberCoupon')->field('id')->where(array('member_id' => $invite['member_id'], 'coupon_id' => $couponID))->find();
                        if (empty($memberCoupon)) {
                            $getCoupon = addMemberCoupon($invite['member_id'], $couponID, 0);
                            M('MemberInvite')->where(['invite_id' => $invite['invite_id']])->save(['is_order' => 1]);
                        }
                    }
                }
            }

            $pay = array(
                'order_id' => $order['order_id'],
                'order_sn' => $order['order_sn'],
                'member_id' => $order['member_id'],
                'pay_id' => $order['pay_id'],
                'pay_code' => $order['pay_code'],
                'pay_time' => $orderArr['pay_time'],
                'pay_amount' => $order['pay_amount'],
                'pay_state' => 1,
                'pay_sn' => $data['transaction_id'],
                'notify_id' => $data['mch_id'],
                'notify_time' => $orderArr['pay_time'],
                'notify_desc' => json_encode($data),
                'create_time' => time(),
            );
            M('OrderPay')->add($pay);

            $goods = M('OrderGoods')->where(['order_id' => $order['order_id']])->select();
            foreach ($goods as $kev => $val){
                $key = C('CACHE_KEY_MENU_GOODS_SELL_NUM') . $val['menu_id'] . '_' . $val['goods_id'];
                $sellNum = S($key);
                S($key, $sellNum + $val['goods_num'], 86400 * 30);
            }
            //trace(json_encode($goods),'','DEBUG',true);
            M('OrderGoods')->where(['order_id' => $order['order_id']])->save(['order_state' => 2, ['update_time' => time()]]);

            $model->commit();
        } catch (\Exception $e) {
            $msg = "订单查询失败";
            $model->rollback();
            return false;
        }
        return true;
    }
}